package com.southminority.ethnic.controller.admin.research;

import com.southminority.ethnic.common.result.PageResult;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.Award;
import com.southminority.ethnic.service.alioss.OssService;
import com.southminority.ethnic.service.research.AwardService;
import com.southminority.ethnic.controller.research.vo.AwardVO;
import com.southminority.ethnic.controller.alioss.vo.OssFileReqVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.springframework.util.StringUtils;

/**
 * 获奖情况管理端控制器
 * 
 * @author SouthMinority
 */
@Slf4j
@Tag(name = "15 - 获奖情况管理API", description = "【后台】科研成果-获奖情况的增删改查接口")
@RestController
@RequestMapping("/admin/research/award")
@CrossOrigin
public class AwardAdminController {

    private final AwardService awardService;
    private final OssService ossService;

    public AwardAdminController(AwardService awardService, OssService ossService) {
        this.awardService = awardService;
        this.ossService = ossService;
    }

    @GetMapping("/page")
    @Operation(summary = "分页和条件查询获奖情况", description = "后台管理使用的获奖列表接口，支持多种条件筛选和分页。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "查询成功")})
    public R<PageResult<AwardVO>> getAwardPage(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页显示数量", example = "10") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键词（标题、项目名）", example = "语音识别") @RequestParam(required = false) String keyword,
            @Parameter(description = "奖项类别", example = "科技成果奖") @RequestParam(required = false) String category,
            @Parameter(description = "奖项级别", example = "一等奖") @RequestParam(required = false) String level,
            @Parameter(description = "状态", example = "1", schema = @Schema(type = "integer", allowableValues = {"1", "0"})) @RequestParam(required = false) Integer status) {
        return R.ok(awardService.getAwardPageForAdmin(page, size, keyword, category, level, status));
    }

    @GetMapping("/detail/{id}")
    @Operation(summary = "获取单个获奖情况的详细信息（用于编辑）", description = "根据获奖ID查询，返回其完整信息。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在")
    })
    public R<AwardVO> getAwardDetail(@Parameter(description = "获奖的唯一ID", example = "1", required = true) @PathVariable Long id) {
        return R.ok(awardService.getAwardDetailForAdmin(id));
    }



    @PostMapping("/create")
    @Operation(summary = "新增一条获奖记录", description = "传入获奖的完整信息（除ID外）来创建一个新的记录。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "创建成功")})
    public R<AwardVO> createAward(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "包含获奖信息的JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Award.class)))
            @org.springframework.web.bind.annotation.RequestBody Award award) {
        log.info("管理员创建获奖情况: Title={}", award.getTitle());
        
        if (award.getTitle() == null || award.getTitle().trim().isEmpty()) {
            return R.fail("奖项名称不能为空");
        }
        
        return R.ok(awardService.createAward(award));
    }

    @PutMapping("/update/{id}")
    @Operation(summary = "根据ID更新获奖信息", description = "提供获奖ID和更新后的信息，对现有记录进行修改。注意：JSON字段应为字符串格式。")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "更新成功"),
            @ApiResponse(responseCode = "404", description = "获奖记录不存在")
    })
    public R<AwardVO> updateAward(
            @Parameter(description = "要更新的获奖ID", example = "1", required = true) @PathVariable Long id,
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "包含更新字段的获奖JSON对象", required = true,
                    content = @Content(schema = @Schema(implementation = Award.class)))
            @org.springframework.web.bind.annotation.RequestBody Award award) {
        log.info("管理员更新获奖情况: ID={}, Title={}", id, award.getTitle());
        return R.ok(awardService.updateAward(id, award));
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "根据ID逻辑删除获奖记录", description = "将指定ID的获奖记录状态设置为-1（已删除）。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "删除成功")})
    public R<Boolean> deleteAward(@Parameter(description = "要删除的获奖ID", example = "1", required = true) @PathVariable Long id) {
        log.info("管理员删除获奖情况: ID={}", id);
        return R.ok(awardService.deleteAward(id));
    }

    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量逻辑删除获奖记录", description = "传入一个ID列表，批量将对应的获奖记录状态设置为-1。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "批量删除成功")})
    public R<Boolean> batchDeleteAwards(
            @RequestBody(description = "包含多个获奖ID的数组", required = true,
                    content = @Content(schema = @Schema(type = "array", implementation = Long.class))) List<Long> ids) {
        log.info("管理员批量删除获奖情况: IDs={}", ids);
        return R.ok(awardService.batchDeleteAwards(ids));
    }

    @PutMapping("/status/{id}")
    @Operation(summary = "更新获奖记录状态", description = "更新单个获奖记录的状态，如启用（1）和禁用（0）。")
    @Parameters({
            @Parameter(name = "id", description = "获奖ID", example = "1", required = true),
            @Parameter(name = "status", description = "新的状态值", example = "0", required = true,
                    schema = @Schema(type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "状态更新成功")})
    public R<Boolean> updateAwardStatus(@PathVariable Long id, @RequestParam Integer status) {
        log.info("管理员更新获奖情况状态: ID={}, Status={}", id, status);
        return R.ok(awardService.updateAwardStatus(id, status));
    }

    @PutMapping("/featured/{id}")
    @Operation(summary = "设置获奖记录重点展示状态", description = "设置或取消单个获奖记录的重点展示状态。")
    @Parameters({
            @Parameter(name = "id", description = "获奖ID", example = "1", required = true),
            @Parameter(name = "isFeatured", description = "是否重点展示", example = "1", required = true,
                    schema = @Schema(type = "integer", allowableValues = {"1", "0"}))
    })
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "设置成功")})
    public R<Boolean> setAwardFeatured(@PathVariable Long id, @RequestParam Integer isFeatured) {
        log.info("管理员设置获奖情况重点展示: ID={}, IsFeatured={}", id, isFeatured);
        return R.ok(awardService.setAwardFeatured(id, isFeatured));
    }

    @PostMapping(value = "/upload-certificate", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传获奖证书图片", description = "上传证书图片文件到OSS，并返回可访问的URL。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "上传成功")})
    public R<String> uploadCertificateImage(@Parameter(description = "包含文件和分类信息的表单") @Valid @ModelAttribute OssFileReqVo ossFileReqVo) {
        // 设置默认分类
        if (!StringUtils.hasText(ossFileReqVo.getClassName())) {
            ossFileReqVo.setClassName("award-certificate");
        }
        log.info("管理员上传获奖证书图片: 分类={}", ossFileReqVo.getClassName());
        String imageUrl = ossService.upload(ossFileReqVo.getFile(), ossFileReqVo.getClassName());
        return R.ok(imageUrl);
    }

    @PostMapping(value = "/upload-photo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传获奖照片", description = "上传照片文件到OSS，并返回可访问的URL。")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "上传成功")})
    public R<String> uploadAwardPhoto(@Parameter(description = "包含文件和分类信息的表单") @Valid @ModelAttribute OssFileReqVo ossFileReqVo) {
        // 设置默认分类
        if (!StringUtils.hasText(ossFileReqVo.getClassName())) {
            ossFileReqVo.setClassName("award-photo");
        }
        log.info("管理员上传获奖照片: 分类={}", ossFileReqVo.getClassName());
        String imageUrl = ossService.upload(ossFileReqVo.getFile(), ossFileReqVo.getClassName());
        return R.ok(imageUrl);
    }
} 
